package com.mtons.core.interfaces.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * ClassName: AbstractDao <br/>
 * Function: TODO. <br/>
 * Reason: TODO. <br/>
 * date: 2016年10月3日 下午5:52:57 <br/>
 * @author Administrator
 * @version @param <PK>
 * @version @param <T>
 * @since JDK 1.6
 */
public abstract class AbstractDao<PK extends Serializable, T> {

	private final Class<T> persistenceClass;

	@SuppressWarnings("unchecked")
	public AbstractDao() {
		this.persistenceClass = (Class<T>) ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
	}
	
	@Autowired
	private SessionFactory sessionFactory;
	
	protected Session getSession(){
		return this.sessionFactory.getCurrentSession();
	}
	

	/**
	 * getByKey: <br/>
	 * TODO<br/>
	 * @author Administrator
	 * @param key
	 * @return
	 * @since JDK 1.6
	 */
	@SuppressWarnings("unchecked")
	public T getByKey(PK key){
		return (T) getSession().get(persistenceClass, key);
	}
	

	/**
	 * persist: <br/>
	 * TODO<br/>
	 * @author Administrator
	 * @param entity
	 * @since JDK 1.6
	 */
	public void persist(T entity){
		getSession().persist(entity);
	}
	

	/**
	 * delete: <br/>
	 * TODO<br/>
	 * @author Administrator
	 * @param entity
	 * @since JDK 1.6
	 */
	public void delete(T entity){
		getSession().delete(entity);
	}
	
	/**
	 * createEntityCriteria: <br/>
	 * TODO<br/>
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	protected Criteria createEntityCriteria(){
		return getSession().createCriteria(persistenceClass);
	}
	
	
}
